package com.itheima.mm.controller;


import com.itheima.mm.pojo.HmArticles;
import com.itheima.mm.pojo.PageResult;
import com.itheima.mm.dto.Result;
import com.itheima.mm.service.ArticlesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/articles")
public class ArticlesController {

    @Autowired
    private HttpServletRequest req;

    @Autowired
    private ArticlesService articlesService;

    /**
     * 查询文章
     * @param keyword  分页条件(非必须)
     * @param state 分页状态(非必须)
     * @param page 页码(必须)
     * @param pagesize  页码大小(必须)
     * @return
     */
    @GetMapping
    public PageResult findPage(String keyword,Integer state,Integer page,Integer pagesize){

       return articlesService.findPage(keyword,state,page,pagesize);
    }

    /**
     * 修改文章状态
     * @param id 修改文章id
     * @param state
     * @return
     */
    @PostMapping("/{id}/{state}")
    public Result updateState(@PathVariable Integer id,@PathVariable Integer state){
      return   articlesService.updateState(id,state);
    }
    /**
     * 删除文章
     */
    @DeleteMapping("/{id}")
    public Result rm(@PathVariable Integer id){
       return articlesService.rm(id);
    }
    /**
     * 编辑文章信息
     * @param id
     * @param hmArticles
     * @return
     */
    @PutMapping("/{id}")
    public Result put(@PathVariable Integer id, @RequestBody HmArticles hmArticles){
       return articlesService.put(id,hmArticles);
    }

    /**
     * 添加文章
     */
    @PostMapping()
    public String add(@RequestBody HmArticles hmArticles){
        HttpSession session = req.getSession();
        Integer id = (Integer) session.getAttribute("id");
        hmArticles.setCreateTime(LocalDateTime.now());
        hmArticles.setCreatorId(id);
        hmArticles.setVisits(0);
        hmArticles.setState(1);
        articlesService.add(hmArticles);
        return "添加成功";
    }

    /**
     * 文章详情
     */
    @GetMapping("/{id}")
    public HmArticles details(@PathVariable Integer id){
        return articlesService.details(id);
    }

}
